using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace SimpleFramework
{
    public static class UnityUIRawImage_Extension
    {
        private static Dictionary<int, long> s_Binder = new Dictionary<int, long>();

        public static void SetTexture(this RawImage comp, string assetPath, bool useNativeSize = false)
        {
            long uuid;
            int instanceID = comp.GetInstanceID();
            if (s_Binder.TryGetValue(instanceID, out uuid))
            {
                Res.Stop(uuid);
                s_Binder.Remove(instanceID);
            }

            s_Binder[instanceID] = Res.Spawn(assetPath, (IResObjectPool pool, object userData) =>
            {
                s_Binder.Remove(instanceID);
                Res.UnSpawn(comp.texture);
                var texture = pool.Spawn<Texture>();
                comp.texture = texture;
                if (useNativeSize)
                    comp.SetNativeSize();
            }, null);
        }

        public static void SetTexture(this RawImage comp, string assetPath, System.Action<RawImage> onComplete)
        {
            long uuid;
            int instanceID = comp.GetInstanceID();
            if (s_Binder.TryGetValue(instanceID, out uuid))
            {
                Res.Stop(uuid);
                s_Binder.Remove(instanceID);
            }

            s_Binder[instanceID] = Res.Spawn(assetPath, (IResObjectPool pool, object userData) =>
            {
                s_Binder.Remove(instanceID);
                Res.UnSpawn(comp.texture);
                var texture = pool.Spawn<Texture>();
                comp.texture = texture;
                onComplete.Invoke(comp);
            }, null);
        }

        public static void ClearTexture(this RawImage comp)
        {
            long uuid;
            int instanceID = comp.GetInstanceID();
            if (s_Binder.TryGetValue(instanceID, out uuid))
            {
                Res.Stop(uuid);
                s_Binder.Remove(instanceID);
            }

            Res.UnSpawn(comp.texture);
            comp.texture = null;
        }
    }
}


